package text

import (
	"bufio"
	"code.google.com/p/gochess/notation/san"
	pos "code.google.com/p/gochess/position"
	"errors"
	"fmt"
	"os"
	"runtime/pprof"
)

func readCommand(in *bufio.Reader) (string, error) {

	input, err := in.ReadString('\n')
	if err != nil {
		return input, err
	}
	// read away newline
	return input[:len(input)-1], err

}

// returns true if the user wants to exit
func ReadMoveFromUser(p *pos.Position, moveOptions []pos.Move) (bool, pos.Move) {

	for {
		fmt.Printf("Your Move as %s ('q' for quit): ", p.SideToMove())
		input, err := readCommand(bufio.NewReader(os.Stdin))
		if err != nil {
			fmt.Println(err)
			pprof.StopCPUProfile()
			os.Exit(0)
		}
		fmt.Println()
		if input == "q" {
			// commands todo
			return true, pos.NoMove
		}
		playersMove, err := san.ParseMove(p, input, moveOptions)
		if err != nil {
			fmt.Printf("%s\n\n", err)
			continue
		}
		i := 0
		for ; i < len(moveOptions) && playersMove != moveOptions[i]; i++ {
		}
		if i == len(moveOptions) {
			err = errors.New("Illegal Move")
			fmt.Printf("%s\n\n", err)
			continue
		}
		return false, playersMove
	}
}
